<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderNo">
              <a-input v-model="model.orderNo" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="订单类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderType">
              <j-dict-select-tag type="list" v-model="model.orderType" dictCode="sd_sales_order_type"
                                 placeholder="请选择订单类型"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderDate">
              <j-date placeholder="请选择单据日期" v-model="model.orderDate" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <j-search-select-tag v-model="model.customerId" dict="crm_customer,cust_full_name,id"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="交货日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryDate">
              <j-date placeholder="请选择交货日期" v-model="model.deliveryDate" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="送达地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryAddress">
              <a-input v-model="model.deliveryAddress" placeholder="请输入送达地址"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="合同号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractNo">
              <j-popup
                v-model="model.contractNo"
                field="contractNo"
                org-fields="id,contract_no,project_id,salesman,customer_id"
                dest-fields="contractId,contractNo,projectId,salesman,customerId"
                code="sd_contract_sale_popup"
                :multi="false"
                :param="{customerId: model.customerId}"
                @input="popupCallback"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
              <j-search-select-tag v-model="model.projectId" dict="quote_project,project_name,id"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="销售员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesman">
              <j-select-user-by-dep v-model="model.salesman" :multi="false"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="16">
            <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark">
              <a-textarea v-model="model.remark" rows="2" placeholder="请输入备注"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="销售明细" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="sdSalesOrderDetailTable.loading"
          :columns="sdSalesOrderDetailTable.columns"
          :dataSource="sdSalesOrderDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          :actionAddButton="false"
          @added = "detailAdded"
          @valueChange = "qtyAndPriceChange"
        >
          <div slot="buttonBefore">
            <div class="action-button">
              <a-button type="primary" icon="plus" @click="chooseContractDetail" :disabled="formDisabled">选单</a-button>
              <span class="gap"></span>
              <a-button type="primary" icon="plus" @click="chooseMaterial" :disabled="formDisabled">新增</a-button>
              <span class="gap"></span>
            </div>
          </div>
        </j-editable-table>
        <j-popup-onl-report ref="contractDetailPopReport" code="sd_contract_detail_sale_popup" multi="true" :param="{contractId: model.contractId}" @ok="contractDetailPopupCallback"/>
        <j-popup-onl-report ref="materialPopReport" code="mdm_popup_bom_material" multi="true" @ok="materialPopupCallback"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

import {getAction} from '@/api/manage'
import {FormTypes, getRefPromise, VALIDATE_NO_PASSED} from '@/utils/JEditableTableUtil'
import {JEditableTableModelMixin} from '@/mixins/JEditableTableModelMixin'
import {validateDuplicateValue} from '@/utils/util'
import moment from "moment";

export default {
  name: 'SdSalesOrderForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      labelCol2: {
        xs: {span: 24},
        sm: {span: 3},
      },
      wrapperCol2: {
        xs: {span: 24},
        sm: {span: 20},
      },
      model: {
        orderType: "01",
        status: "01",
        orderDate: moment(new Date()).format('YYYY-MM-DD'),
      },
      qtyAndPriceModifyFlag: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        orderNo: [
          {required: true, message: '请输入单据编号!'},
        ],
        orderType: [
          {required: true, message: '请输入订单类型!'},
        ],
        customerId: [
          {required: true, message: '请输入客户!'},
        ],
        orderDate: [
          {required: true, message: '请输入单据日期!'},
        ],
        deliveryDate: [
          {required: true, message: '请输入交货日期!'},
        ],
      },
      refKeys: ['sdSalesOrderDetail',],
      tableKeys: ['sdSalesOrderDetail',],
      activeKey: 'sdSalesOrderDetail',
      // 销售订单明细
      sdSalesOrderDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料描述',
            key: 'materialDesc',
            type: FormTypes.popup,
            popupCode: "mdm_popup_bom_material",
            destFields: "materialId,materialNo,materialDesc,unit,contractDetailId",
            orgFields: "material_id,material_code,material_desc,material_unit_code,null_value",
            width: "260px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{required: true, message: '${title}不能为空'}],
          },
          {
            title: '单位',
            key: 'unit',
            type: FormTypes.select,
            dictCode: "mdm_unit,unit_name,unit_code",
            width: "110px",
            placeholder: '请输入${title}',
            defaultValue: '',
            disabled: true,
          },
          {
            title: '订单数量',
            key: 'qty',
            type: FormTypes.inputNumber,
            width: "140px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },

          {
            title: '含税单价',
            key: 'unitPrice',
            type: FormTypes.inputNumber,
            width: "140px",
            placeholder: '请输入${title}',
            defaultValue: '0',
          },
          {
            title: '含税金额',
            key: 'sumPrice',
            type: FormTypes.inputNumber,
            width: "140px",
            placeholder: '请输入${title}',
            defaultValue: '0',
          },
          {
            title: '税率',
            key: 'taxRate',
            type: FormTypes.select,
            dictCode: "mdm_tax_rate,value,value",
            width: "140px",
            placeholder: '请输入${title}',
            defaultValue: '0.13',
          },
          {
            title: '税额',
            key: 'taxPrice',
            type: FormTypes.inputNumber,
            width: "140px",
            placeholder: '请输入${title}',
            defaultValue: '',
            disabled: true,
          },
          {
            title: '交货日期',
            key: 'deliveryDate',
            type: FormTypes.date,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '备注',
            key: 'remark',
            type: FormTypes.input,
            width: "240px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '行号',
            key: 'lineNo',
            type: FormTypes.inputNumber,
            width:"70px",
            placeholder: '请输入${title}',
            defaultValue:'',
            disabled: true,
          },
          {
            title: 'materialId',
            key: 'materialId',
            type: "hidden"
          },
          {
            title: 'materialNo',
            key: 'materialNo',
            type: "hidden"
          },
          {
            title: 'contractDetailId',
            key: 'contractDetailId',
            type: "hidden"
          },

        ]
      },
      url: {
        add: "/sd/salesOrder/add",
        edit: "/sd/salesOrder/edit",
        queryById: "/sd/salesOrder/queryById",
        sdSalesOrderDetail: {
          list: '/sd/salesOrder/querySdSalesOrderDetailByMainId'
        },
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
  },
  watch:{
    'model.deliveryDate':{
      deep: true,
      handler(newVal, oldVal){
        if(newVal){
          let sdSalesOrderDetailTable = this.$refs[this.refKeys[0]];
          let {values} = sdSalesOrderDetailTable.getValuesSync({validate: false});
          if(values){
            for(let item of values){
              if(!item.deliveryDate){
                sdSalesOrderDetailTable.setValues([{rowKey: item.id, values:{deliveryDate: newVal}}])
              }
            }
          }
        }
      }
    }
  },
  methods: {
    addBefore() {
      this.genBillNo("29", "orderNo");
      this.sdSalesOrderDetailTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      // 加载子表数据
      if (this.model.id) {
        let params = {id: this.model.id}
        this.requestSubTableData(this.url.sdSalesOrderDetail.list, params, this.sdSalesOrderDetailTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        sdSalesOrderDetailList: allValues.tablesValue[0].values,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    popupCallback(value, row) {
      this.model = Object.assign(this.model, row);
    },
    chooseContractDetail() {
      if (!this.model.contractId) {
        this.$message.error("请先选择合同！")
        return
      }
      this.$refs.contractDetailPopReport.show();
    },
    contractDetailPopupCallback(rows){
      if(rows && rows.length > 0){
        let sdSalesOrderDetailTable = this.$refs[this.refKeys[0]];
        let oldData = sdSalesOrderDetailTable.getValuesSync();
        let column = this.sdSalesOrderDetailTable.columns.find(col=>col.key === 'materialDesc')
        let orgFieldsArr = ['material_id','material_no','material_desc','unit','unsales_qty','unit_price','unsum_price','id'];
        let destFieldsArr = ['materialId','materialNo','materialDesc','unit','qty','unitPrice','sumPrice','contractDetailId'];
        let addRow, addData
        for(let i =0; i< rows.length; i++){
          if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
            sdSalesOrderDetailTable.add();
          }
          addRow = sdSalesOrderDetailTable.rows[sdSalesOrderDetailTable.rows.length - 1];
          // key转换
          for(let j=0; j<orgFieldsArr.length; j++){
            rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
            if(destFieldsArr[j] !== orgFieldsArr[j]){
              delete rows[i][orgFieldsArr[j]]
            }
          }
          addData = Object.assign({},rows[i])
          //计算税额
          let taxRate = 0.13;
          let sumPrice = addData.sumPrice || 0;
          addData.taxPrice = this.$math.round(this.$math.multiply(this.$math.divide(sumPrice,this.$math.add(1, taxRate)), taxRate));

          sdSalesOrderDetailTable.popupCallback(addData.materialDesc, addData, 'materialDesc'+addRow.id, addRow, column)
        }
      }
    },
    setColDisabled(colIdArr){
      if(colIdArr && colIdArr.length > 0){
        this.$nextTick(()=>{
          for(let colId of colIdArr) {
            let colEl = document.getElementById(colId)
            if(colEl.tagName !== 'INPUT'){
              let inputEl = colEl.getElementsByTagName('INPUT')[0]
              let spanEl = colEl.getElementsByTagName('SPAN')[2]
              if(spanEl){
                spanEl.setAttribute('style', 'display: none')
              }
              colEl = inputEl;
            }
            colEl.setAttribute('disabled', false)
          }
        })
      }
    },
    detailAdded: function (obj) {
      let editTable = this.$refs[this.refKeys[0]];
      let lineNo = this.generateLineNo();
      editTable.setValues([{rowKey: obj.row.id, values:{lineNo: lineNo, deliveryDate: this.model.deliveryDate}}])
    },
    /** 生成行号 */
    generateLineNo(){
      let editTable = this.$refs[this.refKeys[0]];
      let rows = editTable.rows;
      let num = 10;
      if(rows.length > 1){
        let lastId = editTable.getCleanId(rows[rows.length-2].id)
        let {values} = editTable.getValuesSync({ validate: false, rowIds: [lastId] });
        num = Number(values[0].lineNo) + 10
      }
      return num
    },
    chooseMaterial(){
      this.$refs.materialPopReport.show();
    },
    materialPopupCallback(rows){
      if(rows && rows.length > 0){
        let editableTable = this.$refs[this.refKeys[0]];
        let oldData = editableTable.getValuesSync();
        let column = this.sdSalesOrderDetailTable.columns.find(col=>col.key === 'materialDesc')
        let orgFieldsArr = column.orgFields.split(',');
        let destFieldsArr = column.destFields.split(',');
        let addRow, addData
        for(let i =0; i< rows.length; i++){
          if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
            editableTable.add();
          }
          addRow = editableTable.rows[editableTable.rows.length - 1];
          // key转换
          for(let j=0; j<orgFieldsArr.length; j++){
            rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
            if(destFieldsArr[j] !== orgFieldsArr[j]){
              delete rows[i][orgFieldsArr[j]]
            }
          }
          addData = Object.assign({},rows[i])
          editableTable.popupCallback(addData.materialDesc, addData, 'materialDesc'+addRow.id, addRow, column)
        }
      }
    },
    qtyAndPriceChange(parm){
      if(parm && parm['column'] && parm['row'] && parm['target']){
        let cols = ['qty','unitPrice','sumPrice','taxRate','taxPrice'];
        let key = parm.column.key;
        if(cols.includes(key) && !this.qtyAndPriceModifyFlag){
          let valueObj = {}
          let editableTable = parm['target'];
          let qty = parm.row[cols[0]] || 0;
          let taxRate = Number(parm.row[cols[3]] || 0);
          //修改数量
          if(key === cols[0]){
            //计算金额
            let unitPrice = parm.row[cols[1]] || 0;
            let sumPrice = Math.round(unitPrice * qty * 100)/100;
            //计算税额
            let taxMoney = Math.round(sumPrice / (1+taxRate) * taxRate *100)/100
            //
            valueObj = {[cols[2]]: sumPrice, [cols[4]]: taxMoney}
          }
          // 修改单价、金额
          if(key === cols[1] || key === cols[2]){
            let unitPrice, sumPrice
            if(key === cols[1]){
              //计算金额
              unitPrice = parm.row[cols[1]] || 0;
              sumPrice = Math.round(unitPrice * qty * 100)/100;
            }
            if(key === cols[2]){
              //计算单价
              sumPrice = parm.row[cols[2]] || 0;
              unitPrice = qty == 0 ? 0 : Math.round(sumPrice / qty * 100)/100;
            }
            //计算税额
            let taxMoney = Math.round(sumPrice / (1+taxRate) * taxRate *100)/100
            //
            valueObj = {[cols[1]]: unitPrice,[cols[2]]: sumPrice, [cols[4]]: taxMoney}
          }
          // 修改税率
          if(key === cols[3]){
            let sumPrice = parm.row[cols[2]] || 0;
            //计算税额
            let taxMoney = Math.round(sumPrice / (1+taxRate) * taxRate *100)/100
            //
            valueObj = {[cols[4]]: taxMoney}
          }
          //更新
          this.qtyAndPriceModifyFlag = true
          editableTable.setValues([{rowKey: parm.row.id, values: valueObj}]);
          this.qtyAndPriceModifyFlag = false
          // 重新计算统计列
          // editableTable.recalcOneStatisticsColumn(cols[2]);
          // editableTable.recalcOneStatisticsColumn(cols[4]);
        }
      }
    },
  }
}
</script>

<style scoped>
.action-button {
  margin-bottom: 8px;
}

.gap {
  padding-left: 8px;
}
</style>